package com.itzxx.huazhun.ui.device

import android.text.TextUtils
import com.itzxx.huazhun.data.model.DevicesChildBean
import com.itzxx.huazhun.data.repository.HttpRequestCoroutine
import com.itzxx.huazhun.ui.device.add.DevicesAddActivity
import com.itzxx.library_base_ktx.base.viewmodel.BaseViewModel
import com.itzxx.library_base_ktx.callback.livedata.event.EventLiveData
import com.itzxx.library_base_ktx.ext.request
import com.itzxx.library_base_ktx.state.ListDataUiState

class DeviceViewModel : BaseViewModel() {


    //列表数据刷新
    val listDataUiStateLiveData = EventLiveData<ListDataUiState<DevicesChildBean>>()

    private var cursor: String = ""

    fun addDevices() {
        baseContext.value?.let { DevicesAddActivity.startActivity(it) }
    }

    /**
     * 获取数据列表
     */
    fun getList(isRefresh: Boolean) {
        if (isRefresh) {
            cursor = ""
        }
        request({
            HttpRequestCoroutine.detectionEquipmentPage(
                cursor,
                ""
            )
        }, {
            val listDataUiState =
                ListDataUiState(
                    isSuccess = true,
                    isRefresh = isRefresh,
                    isEmpty = it.list.isEmpty(),
                    hasMore = !it.isLast,
                    isFirstEmpty = TextUtils.isEmpty(cursor) && it.list.isEmpty(),
                    listData = it.list
                )
            cursor = it.cursor
            listDataUiStateLiveData.postValue(listDataUiState)
        }, {
            toast(it.errorMsg)
        })
    }
}